import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Image, 
  Typography, 
  Space, 
  Tag, 
  Button, 
  Avatar,
  Divider,
  message,
  Skeleton
} from 'antd';
import { 
  HeartOutlined, 
  HeartFilled,
  ShareAltOutlined,
  EyeOutlined,
  UserOutlined
} from '@ant-design/icons';
import cloudbase from '../../utils/cloudbase';
import styles from './index.module.less';

const { Title, Paragraph } = Typography;

const ArtworkDetail = ({ artworkId }) => {
  const [artwork, setArtwork] = useState(null);
  const [artist, setArtist] = useState(null);
  const [loading, setLoading] = useState(true);
  const [liked, setLiked] = useState(false);
  const [imageUrl, setImageUrl] = useState('');

  // 加载作品详情
  const loadArtworkDetail = async () => {
    try {
      setLoading(true);
      const result = await cloudbase.callFunction('getArtworkDetail', { artworkId });
      
      if (result.code === 0) {
        setArtwork(result.data.artwork);
        setArtist(result.data.artist);
        
        // 获取图片临时访问链接
        if (result.data.artwork.fileID) {
          const url = await cloudbase.getTempFileURL(result.data.artwork.fileID);
          setImageUrl(url);
        }
      }
    } catch (error) {
      console.error('加载作品详情失败:', error);
      message.error('加载作品详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理点赞
  const handleLike = async () => {
    try {
      const result = await cloudbase.callFunction('likeArtwork', { 
        artworkId,
        action: liked ? 'unlike' : 'like'
      });
      
      if (result.code === 0) {
        setLiked(!liked);
        setArtwork(prev => ({
          ...prev,
          likes: liked ? prev.likes - 1 : prev.likes + 1
        }));
        message.success(liked ? '已取消点赞' : '点赞成功');
      }
    } catch (error) {
      console.error('点赞操作失败:', error);
      message.error('操作失败，请稍后重试');
    }
  };

  // 处理分享
  const handleShare = async () => {
    try {
      if (navigator.share) {
        await navigator.share({
          title: artwork.title,
          text: artwork.description,
          url: window.location.href
        });
      } else {
        await navigator.clipboard.writeText(window.location.href);
        message.success('链接已复制到剪贴板');
      }
    } catch (error) {
      console.error('分享失败:', error);
      message.error('分享失败，请稍后重试');
    }
  };

  useEffect(() => {
    if (artworkId) {
      loadArtworkDetail();
    }
  }, [artworkId]);

  if (!artworkId) {
    return null;
  }

  return (
    <div className={styles.detailContainer}>
      <Card className={styles.artworkCard}>
        <Skeleton loading={loading} active>
          {artwork && (
            <>
              {/* 作品图片 */}
              <div className={styles.imageWrapper}>
                <Image
                  src={imageUrl}
                  alt={artwork.title}
                  className={styles.artworkImage}
                />
              </div>

              {/* 作品信息 */}
              <div className={styles.artworkInfo}>
                <Title level={2} className={styles.title}>
                  {artwork.title}
                </Title>

                {/* 艺术家信息 */}
                {artist && (
                  <div className={styles.artistInfo}>
                    <Avatar
                      src={artist.avatar}
                      icon={<UserOutlined />}
                      size={40}
                    />
                    <div className={styles.artistMeta}>
                      <div className={styles.artistName}>{artist.name}</div>
                      <div className={styles.createTime}>
                        {new Date(artwork.createdAt).toLocaleDateString()}
                      </div>
                    </div>
                  </div>
                )}

                <Divider />

                {/* 作品描述 */}
                <Paragraph className={styles.description}>
                  {artwork.description}
                </Paragraph>

                {/* 标签 */}
                <div className={styles.tags}>
                  {artwork.tags && artwork.tags.map(tag => (
                    <Tag key={tag}>{tag}</Tag>
                  ))}
                </div>

                {/* 统计信息 */}
                <div className={styles.stats}>
                  <Space size="large">
                    <span>
                      <EyeOutlined /> {artwork.views || 0} 浏览
                    </span>
                    <span>
                      <HeartOutlined /> {artwork.likes || 0} 喜欢
                    </span>
                  </Space>
                </div>

                {/* 操作按钮 */}
                <div className={styles.actions}>
                  <Button
                    type={liked ? 'primary' : 'default'}
                    icon={liked ? <HeartFilled /> : <HeartOutlined />}
                    onClick={handleLike}
                  >
                    {liked ? '已喜欢' : '喜欢'}
                  </Button>
                  <Button
                    icon={<ShareAltOutlined />}
                    onClick={handleShare}
                  >
                    分享
                  </Button>
                </div>
              </div>
            </>
          )}
        </Skeleton>
      </Card>
    </div>
  );
};

export default ArtworkDetail;